package com.jy.modules.cims.common.controller;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.component.common.service.TCMmQuotaService;
import com.jy.modules.cims.component.quota.CQuotaImpl;
import com.jy.modules.cims.component.quota.ICQuota;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.data.common.dto.TCMmQuotaDTO;
import com.jy.modules.cims.data.dto.ContractAllDto;
import com.jy.modules.cims.data.dto.QuotaDto;
import com.jy.modules.cims.quota.service.QuotaService;
import com.jy.platform.api.sysdict.SysDictAPI;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * @classname: TCMmQuotaController
 * @description: 定义  t_c_mm_quota 控制层
 * @author:  JY-IT-D001
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmQuota")
public class TCMmQuotaController extends BaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmQuotaController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmQuotaService")
    private TCMmQuotaService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.quota.service.QuotaService")
    private QuotaService quotaService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService contractService;
    
    @Autowired
    private SysDictAPI sysDictAPI;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.quota.CQuotaImpl")
    public ICQuota iCQuota;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.quota.CQuotaImpl")
    public CQuotaImpl cQuotaImpl;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/limitRequest/queryTCMmQuota");
        	this.setCurrentQuotaType(model);
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	/*String contractCode=this.getParameterString("contractCode");
        	try{
        		ContractAllDto contractAllDto=contractService.getContractAllInfo(contractCode);
        		model.addObject("contractAllDto", contractAllDto);
        	}catch(Exception e){
        		throw new AbaboonException("查询合约失败：",e);
        	}*/
        	model.setViewName("cims/limitRequest/addTCMmQuota");
        	this.setCurrentQuotaType(model);
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/limitRequest/updateTCMmQuota");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/limitRequest/viewTCMmQuota");
        	this.setCurrentQuotaType(model);
        	try{
        		TCMmQuotaDTO dto=(TCMmQuotaDTO) model.getModel().get("dto");
        		String contractCode=dto.getContractCode();
        		ContractAllDto contractAllDto=contractService.getContractAllInfo(contractCode);
        		model.addObject("contractAllDto", contractAllDto);
        	}catch(Exception e){
        		
        	}
        }else if("toQueryContractPage".equals(operate)){
        	model.setViewName("cims/limitRequest/queryTCMmContract");
        }else if("toWindowContractPage".equals(operate)){
        	String type=this.getParameterString("type");
        	model.addObject("type", type);
        	model.setViewName("cims/limitRequest/windowTCMmContract");
        }
        return model;
    }
    
    /**
     * @author JY-IT-D001
     * @description:查询分页列表
     * @date 2015-01-14 10:07:19
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmQuota")
    @ResponseBody
    public DataMsg queryListTCMmQuota(HttpServletRequest request, TCMmQuotaDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<QuotaDto> list = quotaService.searchQuotaByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    /**
     * @author JY-IT-D001
     * @description:查询分页列表
     * @date 2015-01-14 10:07:19
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/searchListTCMmQuota")
    @ResponseBody
    public DataMsg searchListTCMmQuota(HttpServletRequest request, TCMmQuotaDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	Map<String, Object> searchParams = SearchParamUtil.getSearchParam(dto);
        List<QuotaDto> list = quotaService.searchQuota(searchParams);
        
        dataMsg.setData(list);
        return dataMsg;
    }
    
    /**
     * @author JY-IT-D001
     * @description:新增
     * @date 2015-01-14 10:07:19
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmQuota")
    @ResponseBody
    public DataMsg insertTCMmQuota(HttpServletRequest request, TCMmQuotaDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmQuotaDTO)super.initDto(dto);
        	dto.setQuotaCode("测试的");
            service.insertTCMmQuota(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author JY-IT-D001
     * @description:编辑
     * @date 2015-01-14 10:07:19
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmQuota")
    @ResponseBody
    public DataMsg updateTCMmQuota(HttpServletRequest request, TCMmQuotaDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmQuotaDTO)super.initDto(dto);
           
            service.updateTCMmQuota(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * 删除额度申请，考虑接口调用仅支持单个申请删除
     * @param request
     * @param dataMsg
     * @return 
     * @return DataMsg
     * @author chenguixue
     * @date 2015-1-30-上午10:29:09
     * @update
     */
    @RequestMapping(value = "/deleteTCMmQuota")
    @ResponseBody
    public DataMsg deleteTCMmQuota(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	BaseDTO dto = super.initDto(null);
   	 	String id = (String) this.getParameter("ids"); // 只能为一个
   	 	String quotaType = (String) this.getParameter("quotaType"); // 额度类型
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			QuotaDto quotaDto = iCQuota.getQuotaByCode(id);
			if (CimsConstant.QUOTA_STATUS_UNLOCK.equals(quotaDto.getQuotaStatus())) {
				throw new CimsException(MessageFormat.format("额度申请流水号[{0}]已释放，不可以删除！", new Object[] { id }));
			} else if (CimsConstant.QUOTA_STATUS_WAIT_AUDIT.equals(quotaDto.getQuotaStatus())) {
				service.deleteTCMmQuotaByPrimaryKey(new BaseDTO(), quotaDto.getId().toString());
			} else {
				if (CimsConstant.QUOTATYPE_LOAN.equals(quotaDto.getQuotaType())) {
					// 新增贷款申请信息
					quotaService.addLoantQuotaApply(quotaDto);

					// 删除贷款额度申请信息
					quotaService.deleteLoanQuota(quotaDto);
				} else {
					boolean flag = quotaService.doQuotaCreditBack(quotaDto.getQuotaCode());
					if(!flag){
						quotaService.doQuotaDeleteById(dto, quotaType, id);
					}
				}
			}
			dataMsg.setMsg(CimsExceptionConstant.QUOTA_DELETE_SUCCESS);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error(CimsExceptionConstant.QUOTA_DELETE_FAIL, e);

		}
        
        return dataMsg;
    }
    
    /**
     * 贷款明细释放操作
     * @param request
     * @param dataMsg
     * @return 
     * @return DataMsg
     * @author chenguixue
     * @date 2015-1-30-上午10:29:09
     * @update
     */
    @RequestMapping(value = "/deleteTCMmQuotaDetail")
    @ResponseBody
    public DataMsg deleteTCMmQuotaDetail(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
   	 	String quotaCode = (String) this.getParameter("quotaCode"); // 只能为一个
   	 	String contractNo = (String) this.getParameter("contractNo");
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			QuotaDto quotaDto = iCQuota.getQuotaByCode(quotaCode);
	    	if(CimsConstant.QUOTA_STATUS_UNLOCK.equals(quotaDto.getQuotaStatus())){
	    		throw new CimsException(MessageFormat.format("额度申请流水号[{0}]已释放，不可以删除！", new Object[] { quotaCode}));
	    	}
	    	
			// 删除贷款额度申请信息
			quotaService.deleteLoanQuotaDetail(quotaDto, contractNo);
	    	
			dataMsg.setMsg(CimsExceptionConstant.QUOTA_DELETE_SUCCESS);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error(CimsExceptionConstant.QUOTA_DETAIL_DELETE_FAIL, e);

		}
        
        return dataMsg;
    }
    
    /**
     * @author JY-IT-D001
     * @description:通过主键查询 其明细信息
     * @date 2015-01-14 10:07:19
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmQuotaDTO dto = service.queryTCMmQuotaByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
   @RequestMapping(value = "/queryOneContractAll")
    @ResponseBody
    public DataMsg queryOneContractAll(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) throws AbaboonException{
    	String contractCode=this.getParameterString("contractCode");
    	try{
    		ContractAllDto contractAllDto=contractService.getContractAllInfo(contractCode);
    		dataMsg = super.initDataMsg(dataMsg);
    		dataMsg.setMsg("载入合约成功");
    		dataMsg.setData(contractAllDto);
    	}catch(Exception e){
    		dataMsg.failed("载入合约失败");
    		throw new AbaboonException("载入合约失败",e);
    	}
        return dataMsg;
    }
    
    /* @RequestMapping(value = "/queryOneContractAll")
    public ModelAndView queryOneContractAll(HttpServletRequest request) throws AbaboonException{
    	ModelAndView model=new ModelAndView();
    	String contractCode=this.getParameterString("contractCode");
    	try{
    		ContractAllDto contractAllDto=contractService.getContractAllInfo(contractCode);
    		model.addObject("contractAllDto", contractAllDto);
    	}catch(Exception e){
    		throw new AbaboonException("查询合约失败：",e);
    	}
    	model.setViewName("cims/limitRequest/updateTCMmQuota");
		return model;
    }*/
    
    /**
     * 
     * @Title getContractConstraintHtml
     * @Description TODO
     * @param request
     * @return
     * @throws AbaboonException 
     * ModelAndView 
     * @author lixinyao
     * @date 2015-1-30-上午11:11:18
     * @update 
     * @throws
     */
    @RequestMapping(value = "/getContractConstraintHtml")
    public ModelAndView getContractConstraintHtml(HttpServletRequest request) throws AbaboonException{
    	String contractCode=this.getParameterString("contractCode");
    	ModelAndView model=new ModelAndView("cims/limitRequest/contractConstraint");
    	try{
    		ContractAllDto contractAllDto=contractService.getContractAllInfo(contractCode);
    		model.addObject("contractAllDto", contractAllDto);
    	}catch(Exception e){
    		throw new AbaboonException("载入债权约束失败",e);
    	}
        return model;
    }
    /**
     * 
     * @Title setCurrentQuotaType
     * @Description TODO
     * @param model 
     * void 
     * @author lixinyao
     * @date 2015-1-30-上午11:11:22
     * @update 
     * @throws
     */
    private void setCurrentQuotaType(ModelAndView model){
    	List<Map> quotaTypeDicts=sysDictAPI.getDictByKey("quotaType");
    	String type=this.getParameterString("quotaType");
    	for(Map quotaTypeDict:quotaTypeDicts){
    		String quotaType=(String) quotaTypeDict.get("DICVALUE");
    		if(quotaType.equals(type)){
    			model.addObject("quotaTypeDict", quotaTypeDict);
    		}
    	}
    }
    
    /**贷款实时刷新贷款额度
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/realTimeRefreshLoanData")
    @ResponseBody
    public DataMsg realTimeRefreshLoanData(HttpServletRequest request, QuotaDto dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (QuotaDto)super.initDto(dto);
        	quotaService.doWork(dto);
        	dataMsg.setMsg("刷新成功！");
        	dataMsg.setStatus("ok");
        }catch (Exception e) {
        	if(e.getMessage().indexOf("请求的数据不存在") >-1){
        		dataMsg.setMsg("没有查询到额度申请所分配的数据！");
        		dataMsg.setStatus("failed");
        	}else{
        		dataMsg.failed(e.getMessage());
        		logger.error("执行方法realTimeRefreshLoanData异常：", e);
        	}
        }
        return dataMsg;
    }
    
    /**债权实时刷新债权额度
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/realTimeRefreshCreditData")
    @ResponseBody
    public DataMsg realTimeRefreshCreditData(HttpServletRequest request, QuotaDto dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (QuotaDto)super.initDto(dto);
        	
        	cQuotaImpl.doSingleGetCreditRightQuotaApplyResult(dto);
        	dataMsg.setMsg("刷新成功！");
        	dataMsg.setStatus("ok");
        	return dataMsg;
        }catch (Exception e) {
        	dataMsg.failed(ExceptionUtils.getStackTraceAsString(e));
             // logger.error("执行方法realTimeRefreshCreditData异常：", e.getStackTrace().toString());
            //throw new SysAssistException(CimsExceptionConstant.CREDIT_QUOTA_REAL_TIME_REFRESH_FAILED + ":" + e.getMessage());
            return dataMsg;
        }
    }
}
